//
//  PatternLockPwdManager.m
//  NOAHWM
//
//  Created by Ryan on 13-6-3.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "PatternLockPwdManager.h"
#import "NSString+MD5.h"
#import "JSON.h"

@interface PatternLockPwdManager()

@property (nonatomic, copy) NSString *tempPwd;

@end

@implementation PatternLockPwdManager

@synthesize lockMember;
@synthesize tempPwd;

#pragma mark - Singleton methods
- (id)init
{
    if(self = [super init])
    {
//        self.lockMember = [NYMemberCenterDataManager sharedManager].loginMember;
    }
    return self;
}

- (NYMember *)lockMember
{
    return [NYMemberCenterDataManager sharedManager].loginMember;
}

+ (PatternLockPwdManager *)sharedManager
{
    static PatternLockPwdManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PatternLockPwdManager alloc] init];
    });
    return manager;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [tempPwd release];
    [lockMember release];
    [super dealloc];
}

#pragma mark - Public methods
- (void)saveGesturePassword:(NSString *)pwd
{
    NSString *md5Pwd = [NSString md5HexDigest:pwd];
    self.tempPwd = md5Pwd;
    NSString *suburl = [NSString stringWithFormat:kSaveGesturePwdUrl,@"jsonp",self.lockMember.accountId,md5Pwd,md5Pwd];
    suburl = [suburl stringByAppendingString:@"app000014"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        self.lockMember.gesture_password = self.tempPwd;
        [[NSNotificationCenter defaultCenter] postNotificationName:kHidePatternLockViewNotification object:nil];
    }
    [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

@end
